<template>
  <view class="repari_record">
    <view class="record_item">
      <view class="num" v-if="index == 0">维修记录</view>
      <view class="header">
        <view class="numberTag">{{ index + 1 }}</view>
        <view class="handle">
          <view v-if="(orderStatus !== 4 && msg.userId == userinfo.user_id) ||
        (orderStatus == 4 &&
          msg.userId == userinfo.user_id &&
          updateStatus) 
        " class="handle_item">
            <!-- <view @click="handleAdd" class="addBtn">
              <image src="../../../static/images/add.png" mode=""></image>
              申请配件
            </view> -->
            <block v-if="!isCreateFrom">
              <view @click="handleEdit" class="editBtn">
                <image src="../../../static/images/edit2.png" mode=""></image>
              </view>
              <view @click="handleDel" class="delBtn" v-if="orderStatus !== 4">
                <image src="../../../static/images/del.png" mode=""></image>
              </view>
              <view @click="handleDel" class="delBtn" v-if="orderStatus == 4 && filterateList.length > 1">
                <image src="../../../static/images/del.png" mode=""></image>
              </view>
            </block>
          </view>
        </view>
      </view>
      <view class="content" :style="{ border: isLast ? 'none' : '' }">
        <view class="des">
          <view class="lable">维修类型</view>
          <view>{{ msg.disposeType === 1 ? "设备检修" : "部件更换" }}</view>
        </view>
        <view class="des" v-if="form.disposeDesc">
          <view class="lable">维修描述</view>
          <view>{{ form.disposeDesc }}</view>
        </view>
        <view class="des">
          <view class="lable"></view>
          <view>
            <image-drag-sort :max="9" @changeList="changeImg" :list="disposeImgUrl" :disabled="true"></image-drag-sort>
          </view>
        </view>
        <view class="des">
          <view class="lable">创建人</view>
          <view>{{ msg.malfunctionRecordVO[msg.malfunctionRecordVO.length - 1].userName + ' ' +
        msg.malfunctionRecordVO[msg.malfunctionRecordVO.length - 1].updateTime }} </view>
        </view>
        <!-- <block
          v-if="msg.maintainPartsWorks && msg.maintainPartsWorks.length > 0"
        >
          <view
            :class="[
              'linkPlan',
              msg.repairRecord && pro.status < 7 ? 'warning' : '',
            ]"
            v-for="(pro, i) in msg.maintainPartsWorks"
            :key="i"
            @click="toPartsDetail(pro)"
          >
            <view class="plan_L">
              <view class="L_row">
                <view>关联任务:</view>
                <view>
                  {{ pro.planId }}
                  <text
                    style="
                      color: #fff;
                      background: #0091ff;
                      border-radius: 4rpx;
                      padding: 0 4rpx;
                    "
                    >配件</text
                  >
                </view>
                <view style="color: #666">
                  查看
                  <uni-icons
                    color="#666"
                    size="16"
                    type="arrowright"
                  ></uni-icons>
                </view>
              </view>
              <view class="L_row">
                <view>状态:</view>
                <view class="row_plan">
                  <text
                    :style="{
                      color: resNameColor(pro.planStatus).color,
                      border:
                        '2rpx solid ' + resNameColor(pro.planStatus).color,
                    }"
                    >{{ resNameColor(pro.planStatus).name }}
                  </text>
                  <text
                    v-if="![1, 8, 9].includes(pro.planStatus)"
                    :style="{
                      color: planStatusArr[pro.planStatus - 1].color,
                      border:
                        '2rpx solid ' + planStatusArr[pro.planStatus - 1].color,
                    }"
                    >{{ planStatusArr[pro.planStatus - 1].name }}
                  </text>
                </view>
              </view>
            </view>
          </view>
        </block> -->
      </view>
    </view>
    <!-- 删除维修记录 弹窗提示 -->
    <model title="删除提示" comfireTxt="确定" :maskClick="false" @cancle="partVisible = false" @comfire="comDelPart"
      :visible="partVisible">
      <view style="font-size: 24rpx; margin-bottom: 40rpx; text-align: center">是否确定删除该维修记录相关信息？</view>
    </model>
  </view>
</template>

<script>
import ImageDragSort from '@/components/image-drag-sort/index.vue';
import model from '@/components/model/index.vue';
import { editCHeckRecord } from '@/apis/workOrder.js';
import { update, del, setRecord, fetchDetail } from '@/apis/repair.js';
import { mapState, mapActions } from 'vuex';
export default {
	components: {
		ImageDragSort,
		model,
	},
	props: {
		// 对象数组
		msg: {
			type: Object,
		},
		// 索引值
		index: {
			type: Number,
		},
		// 我自己是否还未签退
		isPlanStatus: {
			type: Boolean,
			default: false,
		},
		// 是否最后一个item
		isLast: {
			type: Boolean,
		},
		// 订单状态,如果是4不可以编辑
		orderStatus: {
			type: Number,
		},
		planId: {
			type: [String, Number],
		},
		elevatorId: {
			type: [String, Number],
		},
		updateStatus: {
			type: Boolean,
		},
		typeObject: {
			type: Object,
			default: ()=>{
				return {};
			}
		},
		id: {
			type: Number,
		},
		planDetailUserArr:{
			type:Array,
			default:[]
		},
		filterateList:{
			type:Array,
			default:[]
		},
	},
	watch: {
		msg(val) {
			this.initData();
		},
	},
	created() {
		this.initData();
	},
	computed: {
		...mapState('user', ['userinfo']),
		showBtn() {
			if (this.msg.maintainPartsWorks && this.msg.maintainPartsWorks.length) {
				if (this.msg.maintainPartsWorks.every((item) => item.planStatus == 9)) {
					return true;
				}
				return false;
			}
			return true;
		},
		// 判断自己转出的单不可编辑
		isCreateFrom() {
			return this.planDetailUserArr.some(item=>item.userId == this.userinfo.user_id && item.createFrom === 2);
		} ,
	},
	data() {
		return {
			partVisible: false,
			disposeImgUrl: [],
			// isEdit: false, //是否整条记录在编辑中
			form: {
				checkContentName: '',
			},
			planOrderStatus: '',
			// isEditDes:false// ,描述是否在编辑中
			planStatusArr: [
				{ name: '审核中', value: 1, color: '#0091FF' },
				{ name: '待报价', value: 2, color: '#0091FF' },
				{ name: '待发货', value: 3, color: '#0091FF' },
				{ name: '待分配', value: 4, color: '#0091FF' },
				{ name: '待更换', value: 5, color: '#0091FF' },
				{ name: '更换中', value: 6, color: '#0091FF' },
				{ name: '已完成', value: 7, color: '#16BF99' },
				{ name: '已关闭', value: 8, color: '#999999' },
				{ name: '已撤回', value: 9, color: '#999999' },
			],
			examineArr: [
				{ name: '审核中', color: '#FA6400', arrStatus: [1, 2, 3] },
				{ name: '审核不通过', color: '#E02020', arrStatus: [8] },
				{ name: '审核通过', color: '#16BF99', arrStatus: [4, 5, 6, 7] },
				{ name: '已撤回', color: '#999999', arrStatus: [9] },
			],
		};
	},
	methods: {
		initData() {
			let msg = JSON.parse(JSON.stringify(this.msg));
			delete msg.malfunctionRecordVO;
			this.form = msg;
			this.form.checkTypeName = this.form.partNames.split('&amp;&amp;');
			let arr = [];
			for (let i = 0; i < this.form.disposeImgUrl.length; i++) {
				this.form.disposeImgUrl[i];
				arr.push(this.form.disposeImgUrl[i].url);
			}
			this.disposeImgUrl = arr;
			// console.log("this.form ", this.planId, this.form);
		},
		changeImg(list) {
			this.disposeImgUrl = list;
		},
		// 删除记录
		async handleDel() {
			console.log(this.isPlanStatus, this.orderStatus, 'this.isPlanStatus');
			if (this.orderStatus < 4 && !this.isPlanStatus) {
				uni.showToast({
					title: '请先签到后再操作',
					icon: 'none',
				});
				return;
			}
			if (this.isCreateFrom) {
				uni.showToast({
					title: '转出工单无法操作',
					icon: 'none',
					mask: true,
				});
				return;
			}
			await this.getDetail();
			if (this.orderStatus === 4 && !this.updateStatus) {
				this.$emit('hadDone');
				return;
			} else {
				this.partVisible = true; // 显示弹窗
			}
		},
		// 确定删除
		comDelPart() {
			del({ ids: this.msg.id }).then((res) => {
				if (res) {
					uni.showToast({
						title: '删除成功',
						icon: 'none',
					});
					this.partVisible = false;
					this.$emit('update', { type: 'del' });
				}
			});
		},
		// 添加配件
		// handleAdd() {
		//   if (this.orderStatus < 4 && !this.isPlanStatus) {
		//     uni.showToast({
		//       title: "请先签到后再操作",
		//       icon: "none",
		//     });
		//     return;
		//   }
		//   let { partNames, partIds, disposeDesc, disposeImgUrl } = this.msg;
		//   let obj = {
		//     partsId: partIds,
		//     partsName: partNames,
		//     desc: disposeDesc,
		//     imgUrls: disposeImgUrl,
		//     disabled: true,
		//   };
		//   hanleToken("set", "partsUpObj", obj);
		//   uni.navigateTo({
		//     url:
		//       `/pageModules/parts/applyParts?malPartId=${this.msg.id}&id=${this.elevatorId}&fromPlanId=${this.planId}` +
		//       "&workOrderType=" +
		//       this.typeObject.workOrderType +
		//       "&emerProcType=" +
		//       this.typeObject.emerProcType,
		//   });
		// },
		// 配件详情
		toPartsDetail(item) {
			uni.navigateTo({
				url: `/subpages/approve/partApprovalDetail?type=3&id=${item.planId}`,
			});
		},
		resStr(name) {
			return name ? name.replaceAll('&amp;&amp;', ' > ') : '';
		},

		resNameColor(pStatus) {
			return (
				this.examineArr.find((item) => item.arrStatus.includes(pStatus)) || {}
			);
		},

		handleEdit() {
			if (this.orderStatus < 4 && !this.isPlanStatus) {
				uni.showToast({
					title: '请先签到后再操作',
					icon: 'none',
				});
				return;
			}
			this.$emit('changeEditStatus', this.msg);
		},
		// 更新内容
		async handleUpdate() {
			await this.getDetail();
			// console.log(this.planOrderStatus, '保存的时候获取任务状态');
			// console.log(this.orderStatus,this.updateStatus,9999);
			if (this.orderStatus == 4 && !this.updateStatus) {
				console.log('完成');

				this.$emit('hadDone');
				// return;
			} else {
				const { disposeDesc } = this.form;
				if (disposeDesc === '' && this.disposeImgUrl.length === 0) {
					uni.showToast({
						title: '图片为必填项',
						icon: 'none',
					});
				} else {
					console.log('提交新建记录');
					uni.showLoading({
						title: '保存中',
						mask: true,
					});
					let imgs = this.disposeImgUrl;
					let arr = [];
					for (let i = 0; i < imgs.length; i++) {
						arr.push({
							url: imgs[i],
							type: 'image',
						});
					}
					this.form.disposeImgUrl = arr;
					this.form.planId = this.planId;
					const all = [
						this.handleDes(this.form, this.msg),
						update({ ...this.form, userId: this.userinfo.user_id }),
					];
					Promise.all(all).then((res) => {
						console.log(res, 'all的值', 88888);
						if (res) {
							// this.isEdit = !this.isEdit;
							setTimeout(() => {
								uni.showToast({
									title: '保存成功',
									icon: 'none',
								});
							}, 200);
							this.$emit('update', { type: 'update' });
						}
					});
				}
			}
		},
		handleDes(res, olddata) {
			return new Promise((resolve) => {
				let result = '';
				let imgUrl = this.disposeImgUrl || [];
				let oimgUrl = [];
				for (let i = 0; i < olddata.disposeImgUrl.length; i++) {
					olddata.disposeImgUrl[i];
					oimgUrl.push(olddata.disposeImgUrl[i].url);
				}
				let recordHistory = res.disposeDesc || '';
				let orecordHistory = olddata.disposeDesc || '';
				if (JSON.stringify(imgUrl) != JSON.stringify(oimgUrl)) {
					if (imgUrl.length == oimgUrl.length) {
						result = result + '更新了照片';
					} else {
						if (imgUrl.length > oimgUrl.length) {
							result =
                result + '上传了' + (imgUrl.length - oimgUrl.length) + '张图片';
						} else {
							result =
                result + '删除了' + (oimgUrl.length - imgUrl.length) + '张图片';
						}
					}
				}
				if (recordHistory != orecordHistory) {
					result = result + (result.length > 0 ? '，' : '');
					result = result + (orecordHistory ? '更新了描述' : '添加了描述');
				}
				if (!result) {
					resolve();
				}

				const params = {
					planId: this.planId,
					userId: this.userinfo.user_id,
					checkHistoryId: this.form.id,
					recordLog: result,
					recordDataValue: this.form,
				};
				console.log('params', params);
				editCHeckRecord(params).then((res) => {
					resolve(res);
				});
			});
		},
		getDetail() {
			return new Promise((resolve) => {
				fetchDetail({ planId: this.planId }).then((res) => {
					if (res) {
						this.planOrderStatus = res.data.status;
						resolve();
					}
				});
			});
		},
	},
};
</script>
<style lang="scss" scoped>
.repari_record {
  background: #f6f7fa;
  padding: 20rpx 20rpx 0;
  border-radius: 8rpx 8rpx 0 0;

  .title {
    font-size: 32rpx;
    color: #333;
    font-weight: 500;
    // padding-bottom: 22rpx;
    padding-left: 20rpx;
  }

  .length {
    text-align: right;
    padding-bottom: 20rpx;
    color: #ccc;
    font-size: 24rpx;
  }

  .record_item {
    // display: flex;
    width: 100%;

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 8rpx;
      padding-top: 22rpx;

      .numberTag {
        display: inline-block;
        width: 40rpx;
        height: 40rpx;
        line-height: 40rpx;
        text-align: center;
        font-weight: normal;
        background: #ddf0ff;
        border-radius: 2px;
        color: #0091ff;
        font-size: 13px;
        margin: 10rpx 0;
      }

      .handle {
        // width: 412rpx;
        display: flex;
        height: 100%;

        .handle_item {
          display: flex;
          justify-content: flex-end;
          // width: 100%;
          padding-top: 2rpx;
          box-sizing: border-box;
          width: 290rpx;
        }

        image {
          width: 32rpx;
          height: 32rpx;
        }

        .addBtn {
          padding-right: 12rpx;
          font-size: 12px;
          color: #666666;
          margin: 0 14rpx 0 10rpx;
        }

        .editBtn {
          justify-content: center;
        }

        .delBtn {
          padding-left: 20rpx;
        }

        view {
          display: flex;
          // flex: 1;
          justify-content: flex-end;
        }

        .saveBtn {
          color: #0091ff;
          width: 100%;
          display: flex;
          align-items: center;
          font-size: 24rpx;

          text {
            margin-left: 4rpx;
          }
        }
      }
    }

    .num {
      font-size: 28rpx;
      color: #333333;
      font-weight: bold;
      border-left: 4rpx solid #0091ff;
      padding-left: 10rpx;
    }

    .content {
      padding-bottom: 20rpx;

      .des {
        display: flex;
        align-items: center;
        font-size: 28rpx;
        color: #333333;
        margin-bottom: 20rpx;

        .lable {
          width: 180rpx;
          color: #999999;
          margin-right: 20rpx;
        }
      }

      .warning {
        border: 2rpx solid #e02020 !important;
      }

      .linkPlan {
        padding: 20rpx 16rpx;
        background: #f6f6f6;
        border-radius: 8rpx;
        margin-top: 20rpx;
        border: 2rpx solid transparent;

        // display: flex;
        .plan_L {
          .L_row {
            margin-bottom: 10rpx;
            font-size: 12px;
            font-weight: 400;
            color: #666666;
            display: flex;

            view:nth-of-type(1) {
              width: 120rpx;
            }

            view:nth-of-type(2) {
              color: #333;
              // width: 500rpx;
              flex: 1;
            }

            .row_plan {
              text {
                display: inline-block;
                padding: 2rpx 6rpx;
                border-radius: 8rpx;
              }

              text:nth-of-type(1) {
                margin-right: 16rpx;
              }
            }
          }

          .L_row:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}
</style>
